<template>
  <div>
    <!-- 搜索栏 -->
    <el-form :inline="true">
      <el-form-item label="标签名称" style="font-weight: bold">
        <el-input style="width: 130px" v-model="tagSearch" placeholder="请输入标签名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search"  @click="searchList" type="primary">查找</el-button>
        <el-button :icon="Refresh"  @click="clearSearch" >重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具栏 -->
    <el-row :span="10">
      <el-button :icon="Plus"  @click="handleAdd" type="primary">新增</el-button>
      <el-button :icon="Delete"  :disabled="!multipleTagSelect.length"  @click="multipleDelete" type="danger">批量删除</el-button>
    </el-row>
    <!-- 表格栏 -->
    <div style="margin-top: 8px">
      <el-table
          max-height="550px"
          border
          :data="state.tags"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column
            width="80"
            align="center"
            label="序号">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="标签名">
          <template #default="scope">
            <el-tag>{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="articleCount" label="文章量" />
        <el-table-column align="center" label="排序" prop="sort" sortable>
          <template #default="scope">
            <el-tag type="warning">{{ scope.row.sort }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间" width="200px" />
        <el-table-column align="center" label="操作" width="220px" fixed="right">
          <template #default="scope">
            <el-button size="small" type="warning" @click="handleTop(scope.$index, scope.row)">
              置顶
            </el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-popconfirm
                confirm-button-text="Yes"
                cancel-button-text="No"
                :icon="QuestionFilled"
                icon-color="orange"
                title="您确定要删除吗?"
                @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页栏 -->
    <div>
      <div class="pagination-block">
        <el-pagination
            v-model:currentPage="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :small="false"
            :disabled="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!--添加修改区域-->
    <el-dialog center :title="title" v-model="dialogFormVisible">
      <el-form  :rules="rules" ref="ruleFormRef" :model="state.tagForm" >
        <el-form-item label="标签名" prop="name" :label-width="120">
          <el-input size="large" v-model="state.tagForm.name"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort" :label-width="120">
          <el-input-number size="large" v-model="state.tagForm.sort"></el-input-number>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" align="center">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAndEdit(ruleFormRef)">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>

import {reactive, ref} from "vue";
import {ElNotification, ElTable, FormInstance, FormRules, ElMessage, ElMessageBox} from "element-plus";
import { Search,Refresh,Plus,Delete,QuestionFilled,} from '@element-plus/icons-vue'
import {add, edit,multipleRemove, remove, top} from "../../api/tag.js";
import request from "../../utils/request.js";

// 表单校验
const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [
    {required: true, message: '必填字段', trigger: 'blur'},
    {min: 2, max: 12, message: '长度限制 2-8', trigger: 'blur'},
  ],
  sort: [
    {required: true, message: '必填字段', trigger: 'blur'},
  ],
})

const state = reactive({
  tags: [],
  tagForm: {},
})
const tagSearch = ref('')

// 批量选中的数据
const multipleTagSelect = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalSize = ref(0)

const title = ref('')
const dialogFormVisible = ref(false)

// 重置表单校验
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const handleEdit = (index: number, row: any) => {
  title.value = '修改标签'
  dialogFormVisible.value = true
  state.tagForm = row
  resetForm(ruleFormRef.value)
}
const handleDelete = (index: number, row: any) => {
  remove(row).then((res:any) => {
    if(res.code == '200' || res.code == 200){
      ElNotification({
        title: 'success',
        message: res.msg,
        type: 'success',
      })
      searchList();
    }else {
      ElNotification({
        title: 'error',
        message: res.msg,
        type: 'error',
      })
    }
  })
}
const handleTop = (index: number, row: any) => {
  top(row).then((res:any) => {
    if(res.code == '200' || res.code == 200){
      ElNotification({
        title: 'success',
        message: res.msg,
        type: 'success',
      })
      searchList();
    }else {
      ElNotification({
        title: 'error',
        message: '置顶失败',
        type: 'error',
      })
    }
  })
}
const handleAdd = () => {
  title.value = '新增标签'
  state.tagForm = {}
  dialogFormVisible.value = true
  resetForm(ruleFormRef.value)
}
const multipleDelete = () => {
  ElMessageBox.confirm(
      '是否进行批量删除?',
      '删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        multipleRemove(multipleTagSelect.value).then((res:any) => {
          if(res.code == '200' || res.code == 200){
            ElNotification({
              title: 'success',
              message: res.msg,
              type: 'success',
            })
            searchList();
          }else {
            ElNotification({
              title: 'error',
              message: res.msg,
              type: 'error',
            })
          }
        })
      })
}
const searchList = () => {
  request.get("/tag/list",{
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      tagSearch: tagSearch.value
    }
  }).then((res:any) => {
    if(res.code == '200' || res.code == 200){
      console.log(res)
      currentPage.value = res.data.current
      pageSize.value = res.data.size
      totalSize.value = res.data.total
      state.tags = res.data.records
    }
  })
}
const clearSearch = (index: number, row: any) => {
  tagSearch.value = '';
  searchList()
}

// 选中复选框后
const handleSelectionChange = (val: any) => {
  multipleTagSelect.value = val
}
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  searchList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  searchList()
}
const addAndEdit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if(state.tagForm.id){
        edit(state.tagForm).then((res:any) => {
          if(res.code == '200' || res.code == 200){
            ElNotification({
              title: 'success',
              message: res.msg,
              type: 'success',
            })
            dialogFormVisible.value = false
            searchList()
          }else {
            ElNotification({
              title: 'error',
              message: '修改失败',
              type: 'error',
            })
            dialogFormVisible.value= false;
            searchList();
          }
        })
      }else{
        add(state.tagForm).then((res:any) => {
          if(res.code == '200' || res.code == 200){
            ElNotification({
              title: 'success',
              message: res.msg,
              type: 'success',
            })
            dialogFormVisible.value = false
            searchList()
          }else {
            ElNotification({
              title: 'error',
              message: '添加失败',
              type: 'error',
            })
            dialogFormVisible.value= false;
            searchList();
          }
        })
      }
    }
  })
}
searchList()
</script>

<style scoped lang="scss">
.pagination-block{
  margin-top: 10px;
  float: right;
}
</style>
